package com.woniuxy.woniumall.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.woniumall.JedisPoolUtil;
import com.woniuxy.woniumall.entity.Catagory;
import com.woniuxy.woniumall.mapper.CatagoryMapper;
import org.springframework.beans.factory.NamedBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import javax.naming.Name;
import java.awt.image.Kernel;
import java.util.List;

@Service
public class CatagoryService {
    @Autowired
    CatagoryMapper catagoryMapper ;

    //@Cacheable(value = "catagory",key = "#root.targetClass+#root.methodName")  //用于查询
    @Cacheable(value = "catagory",keyGenerator = "myKeyGenerator")  //用于查询
    public List<Catagory> findAllCatagory() {
        return catagoryMapper.selectAll();
    }

    /*public List<Catagory> findAllCatagory() {
        //给图书类型 设置一个缓存  每次查询  先查询 缓存  缓存没有在查询数据库
        Jedis jedis = JedisPoolUtil.getInstance().getJedis();
        String catagory = jedis.get("catagory");
        ObjectMapper objectMapper = new ObjectMapper();
        if (catagory == null) {
            List<Catagory> catagories = catagoryMapper.selectAll();
            //把这个集合 转成json
            try {
                String json = objectMapper.writeValueAsString(catagories);
                jedis.set("catagory",json);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            return catagories ;
        }else {
            try {
                List<Catagory> lists = objectMapper.readValue(catagory,List.class);
                return lists ;
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }*/

    @Cacheable(value = "catagory",key = "#id") //#root.args[0]
    public Catagory findCatagoryByKey(int id){
        return catagoryMapper.selectByPrimaryKey(id);
    }

    //插入数据的时候  删除缓存
    /*@CacheEvict(value = "catagory",allEntries=true)//allEntries ：true 操作成功  清空缓存
    public void add(Catagory catagory){
        catagoryMapper.insert(catagory);
    }*/

    //添加完数据之后 ，把添加的对象 缓存到 redis中  要求添加的时候 一定要返回id值
    @CachePut(value = "catagory",key = "#result.id")
    public Catagory add(Catagory catagory){
        catagoryMapper.insert(catagory);
        return catagory ;
    }

    @CachePut(value = "catagory",key = "#result.id")
    public Catagory modify(Catagory catagory){
        catagoryMapper.updateByPrimaryKey(catagory);
        return catagory ;
    }
}
